package 线程间的通信;

import java.util.ArrayList;
import java.util.List;

class MyOneList {
    private List list = new ArrayList();

    public void add() {
	list.add("高");
    };

    public int getSize() {
	return list.size();
    };
}

class MyThread1 extends Thread {
    private MyOneList list;
    private Object lock;

    public MyThread1(MyOneList list, Object lock) {
	this.list = list;
	this.lock = lock;
    }

    public void run() {

	try {
	    synchronized (lock) {

		for (int i = 0; i < 10; i++) {
		    list.add();

		    System.out.println("添加了" + (i + 1) + "元素");
		    if (list.getSize() == 5) {
			lock.notify();
			System.out.println("发出通知");
		    }
		    Thread.sleep(1000);
		}
	    }
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	}

    }
}

class MyThread2 extends Thread {
    private MyOneList list;
    private Object lock;

    public MyThread2(MyOneList list, Object lock) {
	this.list = list;
	this.lock = lock;
    }

    public void run() {
	try {
	    synchronized (lock) {

		
		    //System.out.println(list.getSize());
		    if (list.getSize() < 5) {
			lock.wait();
			System.out.println("==5,线程退出");
			 throw new InterruptedException();
		    }
		
	    }
	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	}
    }
}

public class Test3_1 {
    public static void main(String[] args) {
	MyOneList list = new MyOneList();
	Object object = new Object();
	MyThread1 myThread1 = new MyThread1(list, object);
	myThread1.setName("a");
	myThread1.start();

	MyThread2 myThread2 = new MyThread2(list, object);
	myThread2.setName("b");
	myThread2.start();
    }
}
